package com.share.hope.service.impl;

import com.baidu.aip.imageprocess.AipImageProcess;
import com.share.hope.entity.result.R;
import com.share.hope.service.CommonService;
import com.share.hope.utils.ImageUtil;
import lombok.RequiredArgsConstructor;
import org.json.JSONObject;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.HashMap;

@Service
@RequiredArgsConstructor
public class CommonServiceImpl implements CommonService {

    private final AipImageProcess client;

    @Override
    public R<String> uploadAvatar(MultipartFile file) throws IOException {
        return R.ok(ImageUtil.upload(file));
    }

    @Override
    public void viewImage(String path, HttpServletResponse response) throws IOException {
        ImageUtil.view(path, response);
    }

    @Override
    public void imgAmplify(MultipartFile file, HttpServletResponse response) throws IOException {
        byte[] bytes = file.getBytes();
        JSONObject jsonObject = client.imageQualityEnhance(bytes, new HashMap<>());
        // base64编码图片
        String imageString = jsonObject.getString("image");

        if (StringUtils.hasText(imageString)) {
            returnResponse(file, imageString, response);
        }
    }

    @Override
    public void imgAnime(MultipartFile file, HttpServletResponse response) throws IOException {
        byte[] bytes = file.getBytes();
        JSONObject jsonObject = client.selfieAnime(bytes, new HashMap<>());
        // base64编码图片
        String imageString = jsonObject.getString("image");

        if (StringUtils.hasText(imageString)) {
            returnResponse(file, imageString, response);
        }
    }

    private void returnResponse(MultipartFile file, String imageString, HttpServletResponse response) {
        // 解码base64字符串
        byte[] data = Base64.getDecoder().decode(imageString);

        String suffix = file.getOriginalFilename().split("\\.")[1];
        String filename = "image." + suffix; // 设置文件名，不带扩展名
        String mimeType = "image/" + suffix; // 默认 MIME 类型

        response.setContentType(mimeType);
        response.setHeader("Content-Disposition", "attachment;filename=\"" + filename + "\"");

        // 将解码后的二进制数据写入HttpServletResponse的输出流中
        try {
            response.getOutputStream().write(data);
            response.getOutputStream().flush();
            response.getOutputStream().close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
